# -*- coding: utf-8 -*-

"""
Description: 兰杰柯请求
"""

import json
import os
import pickle
import time
import requests

module_src = os.path.abspath(__file__)
module_dir = os.path.dirname(module_src)


base_url = "https://mall.labgic-ljk.com"


class SessionManager:
    """
    会话维持类
    使用 authorization 添加 token 实现身份认证
    Args:
        session_file (string): 会话文件名
    """

    def __init__(self, session_file: str = "session.json"):
        self.session_file = session_file
        self.cookies = None
        self.session = requests.Session()  # 创建共用会话

        # 添加请求头
        self.session.headers.update(
            {
                "origin": "https://www.labgic.online",
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36",
            }
        )

        # 加载 session
        self.load_session()

    def load_session(self):
        """
        加载登录状态
        """
        if os.path.exists(f"{module_dir}/{self.session_file}"):
            try:
                with open(f"{module_dir}/{self.session_file}", "r") as f:
                    session_data = json.load(f)
                    if session_data.get("accessToken"):
                        self.session.headers.update(
                            {"authorization": session_data["accessToken"]}
                        )
                        if self.check_login():
                            print("✅Token有效")
                        else:
                            print("❌Token失效，重新登录")
                            self.init_login()
                    else:
                        self.init_login()
            except Exception as e:
                print("❌加载 session 失败：", e)
                self.init_login()
        else:
            self.init_login()

    def save_session(self, json_data: dict):
        """持久化当前 session"""
        try:
            session_data = {
                "accessToken": json_data["data"]["accessToken"],
                "refreshToken": json_data["data"]["refreshToken"],
                "expiresIn": json_data["data"]["expiresIn"],
            }
            with open(f"{module_dir}/{self.session_file}", "w") as f:
                json.dump(session_data, f)
            print(f"✅会话数据已保存到 {self.session_file}")
        except Exception as e:
            print(f"❌保存会话数据失败：{e}")

    def check_login(self):
        """
        检查当前 session是否已登录
        通过访问用户资料的方式检测登录状态
        """

        DEATAIL_URL = f"{base_url}/api/mall4cloud_user/user/ma/user_detail_info"
        query = {"companyId": 21265}
        resp = self.session.get(url=DEATAIL_URL, params=query).json()
        if resp["success"] == True:
            return True
        return False

    def get_login_data(self):
        """
        获取登录数据
        Returns:
            dict: 登录返回的JSON数据
        """
        url = f"{base_url}/api/mall4cloud_auth/ua/login"
        data = {"principal": "13250511220", "credentials": "A123456789a", "sysType": 0}
        headers = {"Content-Type": "application/json"}
        response = self.session.post(url, json=data, headers=headers)

        if response.status_code == 200:
            json_data = response.json()
            if json_data.get("success") and json_data.get("data", {}).get(
                "accessToken"
            ):

                # 更新请求头中的 authorization
                self.session.headers.update(
                    {"authorization": json_data["data"]["accessToken"]}
                )
                return json_data
            else:
                raise Exception(f"❌[登录失败] {json_data.get('msg', '未知错误')}")
        else:
            raise Exception(
                f"❌[登录失败] 获取数据失败，状态码：{response.status_code}"
            )

    def init_login(self):
        """
        初始化登录
        """
        max_retries = 5
        for attempt in range(1, max_retries + 1):
            try:
                json_data = self.get_login_data()
                self.save_session(json_data)
                break

            except Exception as e:
                print(f"❌[登录]第{attempt}次尝试失败：{e}")
                if attempt == max_retries:
                    print("❌[登录]已达到最大重试次数，操作失败。")
                else:
                    time.sleep(1)  # 等待1秒后重试


class RequestsHandler(SessionManager):
    """
    请求处理类
    """

    def query_inventory(
        self, erp_code: str, warehouse_code: str = "HNGZ", company_id: int = 21265
    ) -> int:
        """
        查询商品库存

        Args:
            erp_code (str): 商品ERP编码
            warehouse_code (str): 仓库编码，默认为HNGZ 华南广州仓
            company_id (int): 公司ID，默认为21265

        Returns:
            int: 库存数量
        """
        url = f"{base_url}/api/mall4cloud_product/inventory/countErpCodeByWarehouseCode"
        params = {
            "companyId": company_id,
            "erpCode": erp_code,
            "warehouseCode": warehouse_code,
        }

        response = self.session.get(url, params=params)
        if response.json()["success"] == True:
            return response.json()["data"]
        else:
            raise Exception(response.json()["msg"])

    def search_products(
        self,
        keyword: str,
        page_num: int = 1,
        page_size: int = 15,
    ) -> dict:
        """
        LJK商城搜索商品

        Args:
            keyword (str): 搜索关键词
            page_num (int): 页码，默认1
            page_size (int): 每页数量，默认15

        Returns:
            dict: 搜索结果
        """
        url = f"{base_url}/api/mall4cloud_product/ma/spu/ua/search"
        params = {"pageNum": page_num, "pageSize": page_size}

        data = {
            "isSales": 0,  # 是否在售，默认0
            "orderField": 1,  # 排序字段，默认1
            "orderType": 2,  # 排序类型，默认2
            "categoryName": "",
            # "brandNameFirst": "",
            "brandIdFirstList": [435],  # 品牌筛选
            # "brandIdSecondList": [],
            # "categoryId": "",
            # "attrIdList": [],
            # "oneCategoryId": "",
            "text": keyword,
            # "companyId": 21265,  # 公司ID，默认21265
        }
        data = json.dumps(data, separators=(",", ":"))
        response = self.session.post(url, data=data, params=params)
        if response.json()["code"] == "00000":
            return response.json()["data"]
        else:
            raise Exception(response.json()["msg"])

    def get_product_detail(self, spu_id: int):
        """
        根据商品ID获取商品详情

        Args:
            spu_id (int): 商品SPU ID
            office_id (int): 办事处ID，默认33
            company_id (int): 公司ID，默认21265

        Returns:
            dict: 商品详情数据
        """
        url = f"{base_url}/api/mall4cloud_product/ma/spu/getDetailBySpuId"
        params = {
            # "companyId": company_id,
            "spuId": spu_id,
            # "officeId": office_id
        }

        response = self.session.get(url, params=params)
        if response.json()["code"] == "00000":
            return response.json()["data"]
        else:
            raise Exception(response.json()["msg"])

    def exact_search_procode(self, procode: str):
        """
        精确搜索商品
        """
        res = self.search_products(procode)
        if res["total"]:
            # 存在商品列表
            prolist = res["spuList"]
            for pro in prolist:
                for sku in pro["skuList"]:
                    if sku["skuCode"] == procode:
                        # return pro["spuId"]
                        return sku["erpCode"]
        else:
            return None
